package com.clp.protocol.modbus_tcp.client.pipeline;

import com.clp.protocol.modbus_tcp.client.pipeline.check.CheckMbFrmInHandler;
import com.clp.protocol.modbus_tcp.client.pipeline.codec.BytesToMbFrmDecoder;
import com.clp.protocol.modbus_tcp.client.pipeline.codec.CompleteMbFrmDecoder;
import com.clp.protocol.modbus_tcp.client.pipeline.codec.MbFrmToBytesEncoder;
import com.clp.protocol.modbus_tcp.client.pipeline.handler.ControlMasterHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractModbusChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // 解码器，解决粘包半包问题
        ch.pipeline().addLast(new CompleteMbFrmDecoder());
        // 处理器，检查信息内容是否合法
        ch.pipeline().addLast(new CheckMbFrmInHandler());
        // 解码器，将协议内容转换成入站消息对象
        ch.pipeline().addLast(new BytesToMbFrmDecoder());
        // 编码器，将出站消息对象转换成协议内容
        ch.pipeline().addLast(new MbFrmToBytesEncoder());
        // 总控制器,但不实际处理报文，出入站都经过
        ch.pipeline().addLast(new ControlMasterHandler());

        // 自定义处理器
        List<DuplexMasterHandler> extraHandlers = new ArrayList<>();
        addCustomHandlers(extraHandlers);
        extraHandlers.forEach(masterHandler -> ch.pipeline().addLast(masterHandler));
    }

    public abstract void addCustomHandlers(List<DuplexMasterHandler> addToThisList);
}
